'''
Created on Sep 16, 2010

@author: oabalbin
'''
import numpy as np
from collections import deque, defaultdict 

class mirna_record():
    
    def __init__(self):
        self.name=set()
        self.seq=[]
        self.metric=np.zeros(3)
        self.values=np.zeros(7)
        self.counts=0
    
    def add_seq(self, thisseq):
        self.seq.append(thisseq)
    def add_metrics(self, thismet):
        self.metric = np.vstack((self.metric,thismet))
    def add_values(self, thisvals):
        self.values = np.vstack((self.values,thisvals))

def read_file(inputfile_name, BayesTh):
    """
    Protein    SeqLen    S0    S0.1    S0.2    S0.3    S1    S1.1    S1.2    
    BayesFactor    FoldChange    Direction    FDRup    FDRdown    FLAG

    """
    inputfile = open(inputfile_name)
    mirna_dict=defaultdict(mirna_record)    
    header = inputfile.next().strip('\n\t').split('\t')
    for line in inputfile:
        fields = line.strip('\n\t').split('\t')
        name = fields[0].split('_')
        if name[1]=='':
            mirnaseq, mirnaid = name[0], name[0]
        else:
            mirnaseq, mirnaid = name[0], name[1]
        
        if fields[-1] != "FLAG" and float(fields[9])>=BayesTh:
            mirna_dict[mirnaid].name.add(mirnaid)
            mirna_dict[mirnaid].seq.append(mirnaseq)
            mirna_dict[mirnaid].add_metrics(np.array([myfloat(fields[9]),float(fields[10]),float(fields[11])]))
            mirna_dict[mirnaid].add_values(np.array(map(float,fields[2:9])))
            
    inputfile.close()
    
    return mirna_dict, header

def myfloat(x):
    if x=='Inf':
        return np.nan
    else:
        return float(x)

if __name__ == '__main__':
    inputfile_name = '/data/projects/iDEA/Small_RNA/qspecmat_compare_all8.txt_out_report.txt'
    outfile_name = '/data/projects/iDEA/Small_RNA/qspecmat_compare_all8.txt_out_report.txt_summary'
    BayesTh=10.0
    mirna_dict, header = read_file(inputfile_name,BayesTh)
    outfile = open(outfile_name,'w')
    new_header = [['mirnaid'], ["AV_"+ sp for sp in header[2:9]], ["SD_"+ sp for sp in header[2:9]], header[9:12]]
    outfile.write(",".join(sum(new_header,[])).replace(',','\t')+'\n')
    
    for name, mirna in mirna_dict.iteritems():
        line=sum([list(mirna.name), list(np.mean(mirna.values[1:,:],axis=0)), \
                  list(np.std(mirna.values[1:,:],axis=0)), list(np.mean(mirna.metric[1:,:],axis=0))],[])
        outfile.write(",".join(map(str,line)).replace(',','\t')+'\n')
        
    